package com.ls.rbac.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.rbac.config.Result;
import com.ls.rbac.entity.Role;
import com.ls.rbac.entity.User;
import com.ls.rbac.entity.vo.UserRoleVo;
import com.ls.rbac.entity.vo.UserVo;
import com.ls.rbac.service.IRoleService;
import com.ls.rbac.service.IUserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liusheng
 * @since 2025--06--28
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理模块", description = "用户信息接口")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;

    @Operation(summary = "查询用户", description = "根据条件分页查询用户列表")
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result<IPage<User>> page(
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "真实姓名") @RequestParam(required = false) String realName,
            @Parameter(description = "手机号") @RequestParam(required = false) String phone,
            @Parameter(description = "部门ID") @RequestParam(required = false) Integer deptId) {
        User user = new User().setUsername(username).setRealname(realName).setPhone(phone);
        Page<User> page = new Page<>(current, size);
        IPage<User> userPage = userService.pageUsersByDeptId(page, user, deptId);
        return Result.success(userPage);
    }

    @Operation(summary = "获取用户详情", description = "根据ID获取用户详情")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result<User> getUser(@Parameter(description = "用户ID") @PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        return Result.success(user);
    }

    @Operation(summary = "新增用户", description = "添加新用户并分配角色")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:user:add')")
    public Result<Boolean> addUser(@RequestBody UserRoleVo userRoleVo) {
        UserVo userVo = userRoleVo.getUser();
        User user = BeanUtil.copyProperties(userVo, User.class);
        boolean success = userService.addUser(user, userRoleVo.getRoleIds());
        return success ? Result.success(true) : Result.fail("新增用户失败");
    }

    @Operation(summary = "更新用户", description = "更新用户信息和角色")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:user:edit')")
    public Result<Boolean> updateUser(@RequestBody UserRoleVo userRoleVo) {
        UserVo userVo = userRoleVo.getUser();
        if (ObjectUtil.isEmpty(userVo.getAvatar())) {
            userVo.setAvatar(null);
        }
        if (ObjectUtil.isEmpty(userVo.getEmail())) {
            userVo.setEmail(null);
        }
        if (ObjectUtil.isEmpty(userVo.getRealname())) {
            userVo.setRealname(null);
        }
        User user = userService.getById(userVo.getId());
        BeanUtil.copyProperties(userVo, user, CopyOptions.create().ignoreNullValue());
        boolean success = userService.updateUser(user, userRoleVo.getRoleIds());
        return success ? Result.success(true) : Result.fail("更新用户失败");
    }

    @Operation(summary = "删除用户", description = "根据ID删除用户")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result<Boolean> deleteUser(@Parameter(description = "用户ID") @PathVariable Integer id) {
        boolean success = userService.deleteUser(id);
        return success ? Result.success(true) : Result.fail("删除用户失败");
    }

    @Operation(summary = "重置密码", description = "重置用户密码")
    @PutMapping("/reset/password")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    public Result<String> resetPassword(
            @Parameter(description = "用户ID") @RequestParam Integer userId) {
        try {
            String resetPassword = userService.resetPassword(userId);
            return Result.success(resetPassword + "，请使用新密码登录");
        } catch (Exception e) {
            return Result.fail("重置密码失败：" + e.getMessage());
        }
    }

    @Operation(summary = "获取用户角色", description = "获取用户已分配的角色列表")
    @GetMapping("/roles/list/{userId}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result<List<Role>> getUserRoleList(@Parameter(description = "用户ID") @PathVariable Integer userId) {
        List<Role> roleList = roleService.getRolesByUserId(userId);
        return Result.success(roleList);
    }

    @Operation(summary = "分配角色", description = "为用户分配角色")
    @PostMapping("/roles/{userId}")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    public Result<Boolean> assignRoles(
            @Parameter(description = "用户ID") @PathVariable Integer userId,
            @RequestBody List<Integer> roleIds) {
        try {
            userService.assignRolesToUser(userId, roleIds);
            return Result.success(true, "分配角色成功");
        } catch (Exception e) {
            return Result.fail("分配角色失败：" + e.getMessage());
        }
    }

}
